<template>
  <div>
    <!--limit:最大上传数，on-exceed：超过最大上传数量时的操作  -->
    <el-upload
      class="upload-demo"
      action=""
      :on-change="handleChange"
      :on-remove="handleRemove"
      :on-exceed="handleExceed"
      :limit="limitUpload"
      accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
      :auto-upload="false"
    >
      <el-button size="small" type="primary">导入教学计划</el-button>
      <!-- <div slot="tip" class="el-upload__tip">只 能 上 传 xlsx / xls 文 件</div> -->
    </el-upload>

    <!-- 数据展示 -->
    <el-main>
      <el-table :data="da">
        <el-table-column prop="code" label="编号" />
        <el-table-column prop="planname" label="计划名称" />
        <el-table-column prop="teachtype" label="教学类型" />
        <el-table-column prop="plancontent" label="教学方案" />
        <el-table-column prop="timerange" label="教学天数" />
      </el-table>
    </el-main>
    <div>
      <el-button
        type="text"
        @click="handleCancel"
      >
        取消
      </el-button>
      <el-button
        type="primary"
        :loading="importLoading"
        @click="handleImport"
      >
        确认
      </el-button>
    </div>
  </div>
</template>
<script>
import { form } from '@crud/crud'
import { importPlan } from '@/api/teach/plan'
const defaultForm = {
  id: null,
  timerange: 0
}
export default {
  mixins: [form(defaultForm)],
  props: {
    teachType: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      limitUpload: 1,
      fileTemp: null,
      file: null,
      da: [],
      dalen: 0,
      dictType: {},
      importLoading: false
    }
  },
  mounted() {
    this.changeToDict()
  },
  methods: {
    changeToDict() {
      this.teachType.map(v => {
        this.dictType[v.label] = v.value
      })
      console.log(this.dictType)
    },
    handleChange(file, fileList) {
      this.fileTemp = file.raw
      if (this.fileTemp) {
        if (this.fileTemp.name.endsWith('.xlsx') || this.fileTemp.name.endsWith('.xls')) {
          this.importfxx(this.fileTemp)
        } else {
          this.$message({
            type: 'warning',
            message: '附件格式错误，请删除后重新上传！'
          })
        }
      } else {
        this.$message({
          type: 'warning',
          message: '请上传附件！'
        })
      }
    },
    handleCancel() {
      this.$emit('handleCancle')
    },
    handleImport() {
      if (this.dalen === 0) {
        this.$message({
          type: 'warning',
          message: '请导入文件！'
        })
        return
      }
      this.importLoading = true
      const uploaddata = this.da
      // 将教学类型字符转成对应的数字
      uploaddata.map(v => {
        v.teachtype = this.dictType[v.teachtype] - 0
        v.timerange = v.timerange - 0
      })
      console.log(uploaddata)
      importPlan(uploaddata).then(res => {
        this.importLoading = false
        this.$message({
          type: 'success',
          message: res.message
        })
        this.handleCancel()
        // eslint-disable-next-line handle-callback-err
      }, err => {
        this.importLoading = false
        this.$message({
          type: 'error',
          message: '导入失败！'
        })
      })
    },
    handleExceed() {
      this.$message({
        type: 'warning',
        message: '超出最大上传文件数量的限制！'
      })
      return
    },
    handleRemove(file, fileList) {
      this.fileTemp = null
      this.da = []
    },
    importfxx(obj) {
      const _this = this
      // const inputDOM = this.$refs.inputer
      // 通过DOM取文件数据
      this.file = event.currentTarget.files[0]
      var rABS = false // 是否将文件读取为二进制字符串
      var f = this.file
      var reader = new FileReader()
      // if (!FileReader.prototype.readAsBinaryString) {
      FileReader.prototype.readAsBinaryString = function(f) {
        var binary = ''
        var rABS = false // 是否将文件读取为二进制字符串
        // var pt = this
        var wb // 读取完成的数据
        var outdata
        var reader = new FileReader()
        reader.onload = function(e) {
          var bytes = new Uint8Array(reader.result)
          var length = bytes.byteLength
          for (var i = 0; i < length; i++) {
            binary += String.fromCharCode(bytes[i])
          }
          var XLSX = require('xlsx')
          if (rABS) {
            // eslint-disable-next-line no-undef
            wb = XLSX.read(btoa(fixdata(binary)), {
              // 手动转化
              type: 'base64'
            })
          } else {
            wb = XLSX.read(binary, {
              type: 'binary'
            })
          }
          outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]) // outdata就是你想要的东西

          // //此处可对数据进行处理
          const arr = []
          outdata.map(v => {
            const obj = {}
            obj.code = v.Code
            obj.planname = v.planname
            obj.teachtype = v.teachtype
            obj.plancontent = v.plancontent
            obj.timerange = v.timerange
            arr.push(obj)
          })
          _this.da = arr
          _this.dalen = arr.length
          return arr
        }
        reader.readAsArrayBuffer(f)
      }
      if (rABS) {
        reader.readAsArrayBuffer(f)
      } else {
        reader.readAsBinaryString(f)
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
/deep/ .el-input-number .el-input__inner {
  text-align: left;
}
</style>
